#include<iostream>
#include<unistd.h>
#include<cstdlib>
#include<string.h>
#include<string>
#include<stdio.h>

#include"UI.h"
#include"user.h"
#include"connectdb.h"
#include"book.h"
#include"manage.h"
#include"purchaseRecord.h"

using namespace std;
void addbook();
void addusr();
void alterBookInfor();
void deteleBook();
void purchase(user &u);
bool PhoneOfUsr(user &u,const string &phone);

extern ManageBook Man_book;
extern db database;
extern ManageUser Man_user;
extern ManagePurchaseR Man_PurchaseR;
extern vector<book> bookList;
extern vector<user> userList;
UI* UI::m_ui = 0;
/*
主界面的设计:输入账号和密码,根据账户判断是管理员还是用户的登录
*/
void UI::LoginInteface()
{
    while(1)
    {
        system("clear");
        
        cout<<"\t\t\033[35;1mwelcome to OnlineShoppingSystem\033[0m"<<endl;
        cout<<"\n\n\n\n\t\t\t账号:";
        string acount;
        string password;
        cin>>acount;
        cout<<"\t\t\t密码:";
        system("stty -echo");
        cin>>password;
        system("stty echo");
        cout<<endl;
        int check = 0;
        while(0 == acount.compare("admin"))
        {
            if(0 == password.compare("888888"))
            {   UI::Admin();
                return;
            }

            check++;
            if(check>2)
            {
                cout<<"\n登录次数太多啦啦啦"<<endl;
                exit(1);
            }
            else{
                system("clear");
                cout<<"密码错误，请重新输入:";
                system("stty -echo");
                cin>>password;
                system("stty echo");

            }
        }
        UI::usrLogin(acount,password);
        return;
    }
   
}
/*
管理员登录:管理员的账户、密码唯一（3次输入容错机制）
登录成功后:进行书籍的增删改查、用户添加和查看、所有用户的购书记录的查看
*/
void UI::Admin()
{
    while(1)
    {
        system("clear");
          
        cout<<"\n\n\n\t\t\033[35;1m欢迎管理员，您来到网购图书系统\033[0m"<<endl;
        cout<<"---------------------------------------------------------------"<<endl;
        cout<<"\t\t\t1.添加书籍"<<endl;
        cout<<"\t\t\t2.删除书籍"<<endl;
        cout<<"\t\t\t3.修改书籍"<<endl;
        cout<<"\t\t\t4.查看书籍"<<endl;
        cout<<"\t\t\t5.添加会员"<<endl;
        cout<<"\t\t\t6.查看会员"<<endl;
        cout<<"\t\t\t7.查看所有会员的购书记录"<<endl;
        cout<<"\t\t\t0.退出登录"<<endl;
        cout<<"---------------------------------------------------------------"<<endl;
        cout<<"请输入你的选择:";
        int select = 0;
        cin>>select;
        switch(select)
        {
            case 1:
                addbook();
                break;
            case 2:
                deteleBook();
                break;
            case 3:
                alterBookInfor();
                break;
            case 4:
                Man_book.showBookInfor();
                sleep(5);
                break;
            case 5:
                addusr();
                break;
            case 6:
                Man_user.showuserInfor();
                sleep(5);
                break;
            case 7:
                Man_PurchaseR.showPurchaseRecordInfor();
                sleep(2);
                break;
            case 0:
                database.listToDb();
                cout<<"期待我们的下次见面!!!!"<<endl;
                sleep(2);
                return ;
            default:
                break;
            
        }
    }    
}
void addbook()
{
    cout<<"请输入书籍的信息"<<endl;
    getchar();
    cout<<"书名:";
    string name;
    getline(cin,name);
    cout<<"作者:";
    string autor;
    getline(cin,autor);
    cout<<"出版社:";
    string press;
    getline(cin,press);
    cout<<"定价：";
    double price;
    cin>>price;
    cout<<"库存量：";
    int number;
    cin>>number;
    book temp(name,autor,press,price,number);
    Man_book.addBook(temp);

}

void deteleBook()
{
    cout<<"请输入修改书籍的书名:";
    string name;
    getchar();
    getline(cin,name);
    vector<book>::iterator iter = Man_book.findBook(name);
    if(iter == ManageBook::bookList.end())
    {
        cout<<"没有书名为"<<name<<"的图书"<<endl;return;
    }
    Man_book.removeBook(name);
    cout<<"书名为"<<name<<"的图书已经成功删除！！"<<endl;
    sleep(2);
}
void alterBookInfor()
{
    cout<<"请输入修改书籍的书名:";
    getchar();
    string name;
    getline(cin,name);
    vector<book>::iterator iter = Man_book.findBook(name);
    if(iter == ManageBook::bookList.end())
    {
        cout<<"没有书名为"<<name<<"的图书"<<endl;return;
    }
    Man_book.alterBookInfor(name);
     cout<<"书名为"<<name<<"的图书的信息已经成功修改！！"<<endl;
    sleep(2);

}
void addusr()
{
    cout<<"请输入用户的信息"<<endl;
    string name,phone,address;
    int level;
    cout<<"用户姓名:";
    getchar();
    getline(cin,name);
    cout<<"用户为初始化状态,等级为普通会员，消费满足1000元，自动升级"<<endl;
    level = 0;
    cout<<"用户电话号码:";
    getline(cin,phone);
    cout<<"用户地址(此地址将作为用户的买书邮寄地址，请谨慎填写):";
    getline(cin,address);
    user temp(name,level,phone,address);
    Man_user.adduser(temp);
}

/*
用户的登录界面:强大的容错机制（密码不正确重复输入3次，3次都错误认为用户忘记密码，进行重置：为了安全，验证用户的手机号码后四位）
登录成功后:验证是否为首次登录，给出提示信息；验证用户的密码为初始密码,进行密码的修改
登录成功后：查看自己的信息、修改自己电话和寄送地址
查看上线的书籍、购买图示、查看自己的购买记录
*/

void UI::usrLogin(string & acount, string & passwd)
{
    int check = 0;
    vector<user>::iterator iter = Man_user.findUser(atoi(acount.data()));
     if(iter == ManageUser:: userList.end())
     {
        cout<<"无此账号,请核对账号信息"<<endl;
        return;
     }
     while(1)
     {
         if((*iter).m_passwd == passwd)
         
         {
            string LoginTime;
            time_t t;	t=time(NULL);
            char tt[1024]="";
            struct tm *tmper;
            tmper = localtime(&t);
            sprintf(tt,"%d-%d-%d %d:%d:%d",tmper->tm_year+1900,tmper->tm_mon+1,tmper->tm_mday,tmper->tm_hour,tmper->tm_min,tmper->tm_sec);
            LoginTime = tt;
            
            while(1)
            {
                system("clear");
                cout<<"\n\n\n\t\t\033[35;1m欢迎尊敬的会员"<<(*iter).m_name<<",您来到网购图书系统\033[0m"<<endl;
                if((*iter).m_passwd == "12345"){
                    cout<<"系统检测到您的密码为初始密码,为保证您账号的安全,请您修改您的密码:";
                    string passwd;
                    cin>>passwd;
                    (*iter).m_passwd = passwd;
                    cout<<"密码是您登录我们系统的保证，请您妥善保管!!!"<<endl;
                    sleep(2);
                    system("clear");
                }
                if((*iter).m_LoginTime == "0000-00-00 00:00:00"){
                    (*iter).m_balance = 100;cout<<"\033[35;1m\t您首次登录我们网购图书系统\033[0m"<<endl;
                    cout<<"\t尊敬的会员的因您首次登录，系统为赠送100元的购书卷,祝您购书愉快！！\n\t\t消费满1000元后,将升级我们的VIP会员,享受更多优惠！！"<<endl;
                }                
                    
                else
                    cout<<"\033[35;1m\t您上次登录我们网购图书系统的时间:"<<(*iter).m_LoginTime<<"\033[0m"<<endl;               
                cout<<"---------------------------------------------------------------"<<endl;
                cout<<"\t\t1.查看信息"<<endl;
                cout<<"\t\t2.查看所有的上线书籍"<<endl;
                cout<<"\t\t3.查看购买记录"<<endl;
                cout<<"\t\t4.购买图书"<<endl;
                cout<<"\t\t5.修改自己的信息"<<endl;
                cout<<"\t\t0.退出登录"<<endl;
                cout<<"---------------------------------------------------------------"<<endl;
                int select;
                cout<<"请输入你的选择:";
                cin>>select;
                switch(select)
                {
                    case 1:
                        Man_user.showuserInfor(*iter);
                        sleep(2);
                        break;
                    case 3:
                        Man_PurchaseR.showPurchaseRecordInfor(*iter);
                        sleep(2);
                        break;
                    case 4:
                        purchase(*iter);
                        break;
                    case 2:
                        Man_book.showBookInfor();
                        sleep(5);
                        break;
                    case 5:
                        Man_user.alterUserInfor(*iter);
                        //Man_user.alteruserInfor(user &u);
                        sleep(2);
                        break;
                    case 0:
                        (*iter).m_LoginTime = LoginTime;
                        database.listToDb();
                        cout<<"期待我们的下次见面!!!!"<<endl;
                        sleep(2);
                        return;
                    default:
                        break;
                }
            }

        }
        check++;
        if(check>2)
        {
            system("clear");
            cout<<"\n登录次数太多啦啦啦"<<endl;
            cout<<"亲，是不是忘记了您可爱的密码\n您的密码恐怕是不爱你了，它已离您而去"<<endl;
            sleep(1);
            cout<<"是否进行密码的重置！！"<<endl;
            char ch;
            cin>>ch;
            if('y' == ch || 'Y' == ch)
            {
                cout<<"保证您信息的安全性,现对您的手机号码进行验证，请输入您注册时的手机号码的后四位:";
                string phone;
                cin>>phone;
                if(!PhoneOfUsr(*iter,phone))
                {
                    cout<<"信息验证失败,请联系网购系统官方人员!!!"<<endl;
                    system("clear");cout<<"Bye!!!"<<endl;
                    sleep(2);
                    exit(1);
                    
                }
                sleep(3);
                (*iter).m_passwd = "12345";
                cout<<"密码已重置"<<endl;return;
            }
            else
                exit(1);
        }
        
        else
        {
            system("clear");
            cout<<"密码错误，请重新输入:";
            system("stty -echo");
            cin>>passwd;
            system("stty echo");

        }
    }
}
/*
用户的手机号码的后四位验证思想:判断的输入的号码长度是否为4，从后往前依次比较,全部相同才返回真;其他情况皆为假
*/
bool PhoneOfUsr(user &u,const string &phone)
{
    int u_phoneLen = u.m_phone.size();int phoneLen = phone.size();
    while(phoneLen == 4){
        for(int i = u_phoneLen-1, j = phoneLen -1;j >= 0;--i,--j)
        {
            if(u.m_phone[i] != phone[j])
            {
                cout<<"手机号码不正确，身份验证失败!!!"<<endl;
                return false;
            }
        }
        return true;
    }
    cout<<"请输入注册手机号码的后四位!!!"<<endl;
    return false;
}

/*
购买的行为的产生:发起者为用户、操作图书容器、产生消费的记录
购买成功后，记录的产生和自动升级的判断
*/
void purchase(user &u)
{
    vector<book> purchaseBookOfUsr;//购书车----原型:京东、淘宝的购物车思想扩展
    vector<book>::iterator iter; //处理购书车的迭代器
        while(1)
        {
            system("clear");
            cout<<"\n\n\n\t\t\033[35;1m欢迎尊敬的会员"<<u.m_name<<",您来到网购图书系统\033[0m"<<endl;
            cout<<"---------------------------------------------------------------"<<endl;
            cout<<"请输入你想要购买的书籍名字：";
            string name;
            getchar();
            getline(cin,name);
            cout<<"请输入你想要购买"<<name<<"的数量:";
            int number;
            cin>>number;
            vector<book>::iterator it = Man_book.findBook(name);
            if(it == ManageBook::bookList.end())
            {    cout<<"没有这本书,真可惜!!!!"<<endl;
                return ;
            }
            if((*it).m_number - number> 0)
            {
                (*it).m_number -= number;
                book temp(*it);
                temp.m_number = number;
                iter = purchaseBookOfUsr.begin();
                while(iter != purchaseBookOfUsr.end())
                {
                    if(temp.m_name == (*iter).m_name  ){
                        (*iter).m_number += number;
                        break;   
                    }                 
                    iter++;
                }
                if(iter == purchaseBookOfUsr.end())
                    purchaseBookOfUsr.push_back(temp); 
                cout<<"您选择的书籍已经成功的添加至购书车"<<endl;    
                cout<<"\t\t您的宝贝在购书车里静静地等您带它回家！！！"<<endl;          
            }
            else
            {
                cout<<name<<"  这本书太过热销，已经告罄!!!\n请您随时关注我们的系统"<<endl;
                continue;
            }
            
            cout<<"是否选择继续购买书籍:";
            char ch;
            cin>>ch;
            if('y' == ch || 'Y' == ch)
                continue;
            else
                break;
        }
        system("clear");
        cout<<"您的购书车里面的书籍如下:"<<endl;
        double sumOfPrice = 0;
        iter = purchaseBookOfUsr.begin();
        while(iter != purchaseBookOfUsr.end())
        {
            cout<<"书名： "<<(*iter).m_name<<" 作者："<<(*iter).m_autor<<" 出版社:"<<(*iter).m_press<<" 定价："<<(*iter).m_price<<"您购买的数量："<<(*iter).m_number<<endl;
            sumOfPrice += (*iter).m_price*(*iter).m_number;
            
            iter++;
        }
        //sleep(3);
        if(0 == u.m_level)//普通会员
        {
            if(sumOfPrice > 100)
                sumOfPrice *= 0.95;
            if(sumOfPrice < 150)
                sumOfPrice += 10;
        }
        else//VIP会员
        {
            sumOfPrice *= 0.95;
            if(sumOfPrice < 100)
                sumOfPrice += 10;
        }
        u.m_cost += sumOfPrice;
        iter = purchaseBookOfUsr.begin();
        string purchaseNameOfBook = (*iter).m_name;
        while(iter != purchaseBookOfUsr.end())
        {
            if(iter == purchaseBookOfUsr.begin())
            {    ++iter;continue;}
            purchaseNameOfBook = purchaseNameOfBook +"," + (*iter).m_name;            
            ++iter;
        }

        while(1)
        {
                if(u.m_balance > sumOfPrice){
                    u.m_balance -=  sumOfPrice;
                    //付钱的时刻为用户真正的购买时间
                    string purchaseTime;
                    time_t t;	t=time(NULL);
                    char tt[1024]="\0";
                    struct tm *tmper;
                    tmper = localtime(&t);
                    sprintf(tt,"%d-%d-%d %d:%d:%d",tmper->tm_year+1900,tmper->tm_mon+1,tmper->tm_mday,tmper->tm_hour,tmper->tm_min,tmper->tm_sec);
                    purchaseTime = tt;

                    cout<<"尊敬的会员,你此次一共消费 "<<sumOfPrice<<"元"<<endl;
                    sleep(3);
                    cout<<"您的这些书籍我们尽快安排送货,到"<<u.m_address<<endl;
                    sleep(2);
                    cout<<"您的电话号码是："<<u.m_phone<<endl;
                    system("clear");
                    cout<<"请对此次购书经历进行评价：\n 1.非常满意 2.比较满意 3.满意 4.不满意"<<endl;
                    int select;string advise;
                    cin>>select;
                    if(select == 4)
                    {   
                        cout<<"请留下您的宝贵意见,我们会继续改进"<<endl;
                        cin>>advise;
                        cout<<"感谢您的意见,我们相信有了您的真诚的反馈,我们将会做得更好！！"<<endl;
                        sleep(3);
                        //用户意见给出够，生成购买记录                        
                        break;
                    }
                    else{
                        advise = "此次购书的满意度在满意之上,没有给出更多的建议";
                        cout<<"感谢您的评价,我们相信有您的支持才是我们做好服务最大的动力！！"<<endl;
                    }
                    purchaseRecord temp1(u.m_name,purchaseNameOfBook ,purchaseTime,sumOfPrice,advise);
                    Man_PurchaseR.addPurchaseRecord(temp1);
                    sleep(3);
                    break;
                }
                else
                {
                    system("clear");
                    cout<<"余额不足,请充值后,再付款!!!!"<<endl;
                    cout<<"请输入您需要充值的金额:"<<endl;
                    double balance;
                    cin>>balance;
                    cout<<"您充值的金币,正在前往你的账户"<<endl;
                    sleep(3);
                    u.m_balance += balance;
                }
        }
        if(u.m_cost > 1000)
        {
            u.m_level = 1;
            system("clear");
            cout<<"由于您对我们的网购系统的长期支持!!!现将您的等级提升为我们的VIP会员!!!\n享受更多优惠,尽在网购系统!!!"<<endl;
            sleep(4);
        }
    
    
}